package com.liuhuanss.voiceprint.controller;

import com.liuhuanss.voiceprint.dto.ApiResponse;
import com.liuhuanss.voiceprint.entity.User;
import com.liuhuanss.voiceprint.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理控制器
 * 
 * @author liuhuanss
 * @version 1.0
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
@Slf4j
public class AdminController {

    @Autowired
    private UserService userService;

    /**
     * 获取系统统计信息
     * 
     * @return 统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getSystemStats() {
        try {
            log.info("收到获取系统统计信息请求");
            
            long totalVoiceprintUsers = userService.countVoiceprintEnabledUsers();
            List<User> allVoiceprintUsers = userService.getAllVoiceprintEnabledUsers();
            
            Map<String, Object> stats = new HashMap<>();
            stats.put("totalVoiceprintUsers", totalVoiceprintUsers);
            stats.put("activeVoiceprintUsers", allVoiceprintUsers.size());
            stats.put("systemStatus", "运行中");
            stats.put("lastUpdated", java.time.LocalDateTime.now());
            
            return ResponseEntity.ok(ApiResponse.success("获取统计信息成功", stats));
        } catch (Exception e) {
            log.error("获取系统统计信息失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage(), "GET_STATS_FAILED"));
        }
    }

    /**
     * 获取所有启用声纹识别的用户
     * 
     * @return 用户列表
     */
    @GetMapping("/voiceprint-users")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getVoiceprintUsers() {
        try {
            log.info("收到获取声纹用户列表请求");
            
            List<User> users = userService.getAllVoiceprintEnabledUsers();
            
            List<Map<String, Object>> userList = users.stream().map(user -> {
                Map<String, Object> userInfo = new HashMap<>();
                userInfo.put("userId", user.getId());
                userInfo.put("username", user.getUsername());
                userInfo.put("email", user.getEmail());
                userInfo.put("voiceprintFeatureId", user.getVoiceprintFeatureId());
                userInfo.put("voiceprintGroupId", user.getVoiceprintGroupId());
                userInfo.put("createdAt", user.getCreatedAt());
                userInfo.put("updatedAt", user.getUpdatedAt());
                return userInfo;
            }).collect(Collectors.toList());
            
            return ResponseEntity.ok(ApiResponse.success("获取声纹用户列表成功", userList));
        } catch (Exception e) {
            log.error("获取声纹用户列表失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage(), "GET_VOICEPRINT_USERS_FAILED"));
        }
    }

    /**
     * 系统健康检查
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public ResponseEntity<ApiResponse<Map<String, Object>>> healthCheck() {
        try {
            Map<String, Object> health = new HashMap<>();
            health.put("status", "UP");
            health.put("timestamp", java.time.LocalDateTime.now());
            health.put("version", "1.0.0");
            health.put("description", "AI声纹识别登录系统");
            
            // 检查数据库连接
            try {
                userService.countVoiceprintEnabledUsers();
                health.put("database", "UP");
            } catch (Exception e) {
                health.put("database", "DOWN");
                health.put("databaseError", e.getMessage());
            }
            
            return ResponseEntity.ok(ApiResponse.success("系统健康", health));
        } catch (Exception e) {
            log.error("健康检查失败", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage(), "HEALTH_CHECK_FAILED"));
        }
    }
}